package com.example.sunnyweather.logic.ui.place

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.example.sunnyweather.logic.Repository
import com.example.sunnyweather.logic.model.Place

//ViewModel相当于逻辑层和UI层之间的一个桥梁，与界面有关的数据放在这里，旋转的时候不会丢失
class PlaceViewModel : ViewModel() {
    private val searchLiveData = MutableLiveData<String>()
    val placeList = ArrayList<Place>()

    // Transformations.switchMap 将观察searchLiveData的query的LiveData转换为placeLiveData，placeLiveData
    // 本来Observer的泛型是query:String ，这里转换了一下 placeLiveData的观察者得到的结果是Result<List<Place>>
    val placeLiveData = Transformations.switchMap(searchLiveData) // 来观察searchLiveData，将仓库层返回的LiveData对象转换成一个可供Activity观察的LiveData对象
    { query ->
        Repository.searchPlaces(query)
    }
    fun searchPlaces(query: String) {
        searchLiveData.value = query //这里只改变value，没有直接调用仓库层，上面观察的会去执行
    }

    fun savePlace(place: Place) = Repository.savePlace(place)
    fun getSavedPlace() = Repository.getSavedPlace()
    fun isPlaceSaved() = Repository.isPlaceSaved()

}